package com.ken.app.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Author: Liuk
 * Mail: leo_work@aliyun.com
 * Date: 2017/8/15 0015
 * Desc: 客户端信息认证
 */
@Component
@Slf4j
public class MyClientService implements ClientDetailsService {

    private static final int TOKEN_OUT_TIME = 1*60*60*1000;

    private static final int REFRESH_TOKEN_OUT_TIME = 2*60*60*1000;

    /**
     * 验证客户端是否存在
     * @param clientId
     * @return
     * @throws ClientRegistrationException
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        BaseClientDetails details = new BaseClientDetails();
        details.setClientId(clientId);//客户端ID
        details.setClientSecret("Work2017");//客户端密码
        details.setAuthorizedGrantTypes(Arrays.asList("authorization_code","password","refresh_token","implicit") );//认证类型
        details.setScope(Arrays.asList("read","trust","write"));//授权用户的操作权限
        details.setResourceIds(Arrays.asList("rest_api"));//资源ID
        Set<GrantedAuthority> authorities = new HashSet<>();
//        authorities.add(new SimpleGrantedAuthority("ROLE_CLIENT")); //资源权限
        details.setAuthorities(authorities);
        details.setAccessTokenValiditySeconds(120);//token有效期为1小时
        details.setRefreshTokenValiditySeconds(160);//刷新token有效期为2小时
        log.info("..... 加载客户端信息");
        return details;
    }
}
